<?php
defined( '_VALID_MOS' ) or die( 'Restricted access' );

require_once( $mainframe->getPath( 'admin_html' ) );
require_once( $mainframe->getPath( 'class' ) );

$cid = josGetArrayInts( 'cid' );

switch ($task) {
	case 'new':
		editCatphone( $option, 0 );
		break;

	case 'edit':
		editCatphone( $option, $cid[0] );
		break;

	case 'editA':
		editCatphone( $option, $id );
		break;

	case 'save':
		saveCatphone( $option, $id );
		break;

	case 'remove':
		removeCatphone( $cid, $option );
		break;

	case 'cancel':
		cancelCatphone( $option );
		break;
		
	case 'publish':
		changeCatphone( $cid, 1, $option );
		break;

	case 'unpublish':
		changeCatphone( $cid, 0, $option );
		break;	
		
	case 'orderup':
		orderCatphone( intval( $cid[0] ), -1, $option );
		break;

	case 'orderdown':
		orderCatphone( intval( $cid[0] ), 1, $option );
		break;	

	default:
		showCatphone( $option );
		break;
}

/**
* Compiles a list of records
* @param database A database connector object
*/
function showCatphone( $option ) {
	global $database, $mainframe, $mosConfig_list_limit;

	$id 		= intval( $mainframe->getUserStateFromRequest( "id{$option}", 'id', 0 ) );
	$limit 		= intval( $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $mosConfig_list_limit ) );
	$limitstart = intval( $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 ) );
	$search 	= $mainframe->getUserStateFromRequest( "search{$option}", 'search', '' );
	if (get_magic_quotes_gpc()) {
		$search	= stripslashes( $search );
	}

	if ( $search ) {
		$where[] = "cd.name LIKE '%" . $database->getEscaped( trim( strtolower( $search ) ) ) . "%'";
	}
	if ( $id ) {
		$where[] = "cd.id = " . (int) $id;
	}
	if ( isset( $where ) ) {
		$where = "\n WHERE ". implode( ' AND ', $where );
	} else {
		$where = '';
	}

	// get the total number of records
	$query = "SELECT COUNT(*)"
	. "\n FROM #__catphone AS cd"
	. $where
	;
	$database->setQuery( $query );
	$total = $database->loadResult();

	require_once( $GLOBALS['mosConfig_absolute_path'] . '/administrator/includes/pageNavigation.php' );
	$pageNav = new mosPageNav( $total, $limitstart, $limit  );

	// get the subset (based on limits) of required records
	$query = "SELECT cd.*"
	. "\n FROM #__catphone AS cd"	
	. $where
	. "\n ORDER BY cd.ordering, cd.name ASC"
	;
	$database->setQuery( $query, $pageNav->limitstart, $pageNav->limit );
	$rows = $database->loadObjectList();		// build list of categories
	$javascript = 'onchange="document.adminForm.submit();"';
	$lists['id'] = mosAdminMenus::ComponentCategory( 'id', 'com_Catphone', intval( $id ), $javascript );

	HTML_Catphone::showCatphone( $rows, $pageNav, $search, $option, $lists );
}

/**
* Compiles information to add or edit
* @param integer The unique id of the record to edit (0 if new)
*/
function editCatphone( $option, $id ) {
	global $database, $my, $mosConfig_absolute_path;

	$row = new mosCatphone( $database );
	// load the row from the db table
	$row->load( (int)$id );

	// fail if checked out not by 'me'
	if ($row->isCheckedOut( $my->id )) {
		mosRedirect( 'index2.php?option='. $option, 'The module $row->name is currently being edited by another administrator.' );
	}

	if ($id) {
		$row->checkout( $my->id );
	} else {
		// initialise new record
		$row->id 	= intval( mosGetParam( $_POST, 'id', 0 ) );
	}

	// build the html select list for ordering
	$query = "SELECT *"
	. "\n FROM #__catphone"
	. "\n WHERE published >= 0"
	. "\n AND id = " . (int) $row->id
	. "\n ORDER BY ordering"
	;
	$lists['ordering'] 			= mosAdminMenus::SpecificOrdering( $row, $id, $query, 1 );		if ($row->id!=0){		$sql = "SELECT id,title FROM #__sections WHERE published=1 AND id!=".$row->sectionid." ORDER BY ordering ASC, id DESC";		$database->setQuery($sql);		$lsSection = $database->loadObjectList();	}else{		$sql = "SELECT id,title FROM #__sections WHERE published=1 ORDER BY ordering ASC, id DESC";		$database->setQuery($sql);		$lsSection = $database->loadObjectList();	}
	HTML_Catphone::editCatphone( $row, $option, $lists, $lsSection );
}

/**
* Saves the record on an edit form submit
* @param database A database connector object
*/
function saveCatphone( $option, $id ) {
	global $database, $my, $mosConfig_absolute_path, $mosConfig_live_site;		
	
	//Ham kiem tra la so
	function isNaN( $var ) {
	    return !ereg ("^[-]?[0-9]+([\.][0-9]+)?$", $var);
	}
		
	$row = new mosCatphone( $database );
	if (!$row->bind( $_POST )) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}
	if (!$row->check()) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}
	if (mosGetParam($_REQUEST, 'show', 0)){
		$row->show = 1 ;
	}else{
		$row->show = 0 ;
	}
	$uploaddir = $mosConfig_absolute_path."/administrator/components/com_catphone/uploads/";
	if ($id!=0){
		$query = "SELECT * FROM jos_catphone WHERE id=".$id;
		$rs = mysql_query($query);
		$arr = mysql_fetch_array($rs);			
		$img = $arr['img'];
								
		//Upload file  		
		$upload = $uploaddir . basename($_FILES['img']['name'],"");		
		if ($_FILES['img']['tmp_name']!=''){
			if(file_exists($uploaddir.$img)) {
			   @unlink($uploaddir.$img);			  
			}
			if (move_uploaded_file($_FILES['img']['tmp_name'], $upload)) {
				$row->img = basename($_FILES['img']['name'],"");							
			}				
		}														
		if (!$row->store()) {
			echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
			exit();
		}				
		mosRedirect( "index2.php?option=$option" );		
	}
	else{
		//Upload file  																
		$upload = $uploaddir . basename($_FILES['img']['name'],"");		
		if(move_uploaded_file($_FILES['img']['tmp_name'], $upload)){			
			$row->img = basename($_FILES['img']['name'],"");																		
		}				
		if (!$row->store()) {
			echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
			exit();
		}				
		mosRedirect( "index2.php?option=$option" );		
	}
	mosRedirect( "index2.php?option=$option" );
}

/**
* Deletes one or more records
* @param array An array of unique category id numbers
* @param string The current url option
*/
function removeCatphone( $cid, $option ) {
	global $database, $mosConfig_absolute_path;
	
	if (!is_array( $cid ) || count( $cid ) < 1) {
		echo "<script> alert('Select an item to delete'); window.history.go(-1);</script>\n";
		exit;
	}
	if (count( $cid )) {		
		mosArrayToInts( $cid );
		$cids = 'id=' . implode( ' OR id=', $cid );

		$sql = "SELECT * FROM #__catphone"
		. "\n WHERE ( $cids )"
		;				
		$arr = mysql_fetch_array(mysql_query($sql));		
								
		$path = $mosConfig_absolute_path.'/administrator/components/com_Catphone/uploads/';
		if(file_exists($path.$arr['img'])) {
	       @unlink($path.$arr['img']);
	    }		
														
		$query = "DELETE FROM #__catphone"
		. "\n WHERE ( $cids )"
		;
		$database->setQuery( $query );
		if (!$database->query()) {
			echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		}						
	}
	mosRedirect( "index2.php?option=$option" );
}

/**
* Cancels an edit operation
* @param string The current url option
*/
function cancelCatphone( $option ) {
	global $database;
	$row = new mosCatphone( $database );
	$row->bind( $_POST );
	$row->checkin();
	mosRedirect( "index2.php?option=$option" );
}


//Change published
function changeCatphone( $cid=null, $state=0, $option ) {
	global $database, $my;

	josSpoofCheck();

	if (!is_array( $cid ) || count( $cid ) < 1) {
		$action = $state ? 'publish' : 'unpublish';
		mosErrorAlert( "Select an item to $action" );
	}

	mosArrayToInts( $cid );
	$cids = 'id=' . implode( ' OR id=', $cid );

	$query = "UPDATE #__catphone"
	. "\n SET published = " . (int) $state
	. "\n WHERE ( $cids )"	
	;
	$database->setQuery( $query );
	if (!$database->query()) {
		echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		exit();
	}	

	mosRedirect( "index2.php?option=$option" );
}


//Ordering
function orderCatphone( $uid, $inc, $option ) {
	global $database;

	$row = new mosCatphone( $database );
	$row->load( (int)$uid );
	$row->updateOrder();
	$row->move( $inc, "published >= 0" );
	$row->updateOrder();

	mosRedirect( "index2.php?option=$option" );
}
?>